import { t } from 'i18next'
import React, { forwardRef, useImperativeHandle } from 'react'
import { Modal, Select, Button, Input } from '@kedacom/react-next'
import { StyledWrap, StyledVmpSelectItem, StyledVmpPlanModal } from './style'
import { Poll, SelectItem } from '../interface'
import useService from './service'
import { getCheckPreNameRule } from '@/utils'
import { useGlobalStore } from '@/store/global'

export interface VmpPlanProps {
	disabled?: boolean
	getPollParam: () => Poll | null
	testPollParam: () => boolean
}
export interface PlanRef {
	getValue: () => SelectItem
}
const VmpPlan = forwardRef((props: VmpPlanProps, ref: React.Ref<PlanRef>) => {
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	const { disabled, getPollParam, testPollParam } = props
	const {
		inputRef,
		planOptions,
		planValue,
		changePlan,
		deletePlan,
		isSavePlanOpen,
		setIsSavePlanOpen,
		savePlanClick,
		savePlan,
		name,
		setName,
	} = useService({ getPollParam, testPollParam })
	useImperativeHandle(ref, () => ({
		getValue() {
			return planOptions.find((item) => item.value === planValue) as SelectItem
		},
	}))
	return (
		<StyledWrap className="mcc-vmp-plan-wrap">
			<span className="label">{t('电视墙预案')}</span>
			<Select
				width={115}
				options={planOptions}
				value={planValue}
				onClick={(e, v) => changePlan(v)}
				disabled={disabled}
				optionRender={(option, selected) => (
					<StyledVmpSelectItem className={selected ? 'selected' : ''}>
						<span className="select-icon"></span>
						{option.label}
						{option.value !== '0' && (
							<span className="delete-icon" onClick={(e) => deletePlan(e, option as SelectItem)}>
								×
							</span>
						)}
					</StyledVmpSelectItem>
				)}
			/>
			<Button className="savePlan" onClick={savePlanClick}>
				{t('保存预案')}
			</Button>
			<Modal
				open={isSavePlanOpen}
				title={t('保存预案')}
				width={400}
				height={300}
				okText={t('保存')}
				onOk={savePlan}
				onCancel={() => {
					setIsSavePlanOpen(false)
					setName('')
				}}
				cancelText={t('取消')}
			>
				<StyledVmpPlanModal>
					<div className="label">{t('预案名称')}</div>
					<Input
						width={250}
						placeholder={t('请输入预案名称')}
						focusMsg={t('预案名称最多可输入16个字符')}
						innerRef={inputRef}
						maxLength={16}
						rule={{
							required: {
								showIcon: false,
								msg: t('预案名称不能为空'),
							},
							regular: getCheckPreNameRule(SWITCH.characterLimit),
						}}
						value={name}
						onChange={(e, v) => setName(v)}
					/>
				</StyledVmpPlanModal>
			</Modal>
		</StyledWrap>
	)
})
export default VmpPlan
